import React from 'react'
import { Spin, Alert, Pagination } from 'antd';
import fetchJsonp from 'fetch-jsonp';
import MovieItem from "./MovieItem.jsx";

export default class MovieList extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      movie: [],
      nowPage: parseInt(props.match.params.page) || 1,
      nowType: props.match.params.type || 'in_theaters' ,
      nowSize: 2,
      total: 0,
      isLoading: true
    }
  }
  
  // 尚未渲染页面之前获取数据
  componentWillMount() {
    this.loadMovieListByTypeAndPage()
  }
  
  // 切换侧边目录
  componentWillReceiveProps(nextProps) {
    this.setState({
      nowPage: parseInt(nextProps.match.params.page) || 1,
      nowType: nextProps.match.params.type || 'in_theaters' ,
      isLoading: true
    },function () {
      this.loadMovieListByTypeAndPage()
    })
  }
  
  // 渲染
  render(){
    return <div>
      {this.isload()}
    </div>
  }
  
  // 加载数据，并且获取数据后，隐藏加载样式
  loadMovieListByTypeAndPage = () => {
    // const start = this.state.nowPage*this.state.nowSize-(this.state.nowSize-1)
    // const url = `http://api.douban.com/v2/movie/${this.state.nowType}?apikey=0df993c66c0c636e29ecbb5344252a4a&start=${start}&count=${this.state.nowSize}`
    // fetchJsonp(url)
    //   .then(response => response.json())
    //   .then(data => {
    //     this.setState({
    //       movie: data.subjects,
    //       total: data.total,
    //       isLoading: false
    //     })
    //   })
    
    const data = require('../test_data/in_theaters.json')
    setTimeout(()=>{
      this.setState({
        movie: data.subjects,
        total: data.total,
        isLoading: false
      })
    },1000)
  }
  
  // 正在加载的加载样式
  isload = () => {
    if(this.state.isLoading){
      return <Spin tip="Loading...">
        <Alert
          message="电影正在加载"
          description="精彩内容马上呈现..."
          type="info"
        />
      </Spin>
    } else {
      return <div style={{display:'flex',flexWrap:'wrap'}}>
        {this.state.movie.map((item,i) => {
          return <div key={i}>
            <MovieItem {...item} history={this.props.history}></MovieItem>
          </div>
        })}
        {/* 页码 */}
        <Pagination defaultCurrent={this.state.nowPage} pageSize={this.state.nowSize}
                    total={this.state.total} pageSizeOptions={['2','5','10','20']}
                    onChange={this.changePage} onShowSizeChange={this.changeSize}/>
      </div>
    }
  }
  
  // 页码改变
  changePage = (page, pageSize) => {
    this.props.history.push('/movie/' + this.state.nowType + '/' + page)
    this.setState({
      nowPage: parseInt(page),
      nowSize: parseInt(pageSize),
      isLoading: true
    },function () {
      this.loadMovieListByTypeAndPage()
    })
  }
  
  // 每页数量改变
  changeSize = (current, size) => {
    this.setState({
      nowPage: parseInt(current),
      nowSize: parseInt(size),
      isLoading: true
    },function () {
      this.loadMovieListByTypeAndPage()
    })
    
  }
}
